package managedbean.RawMaterialPurchase;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import managedbean.Workspace.FileUploadManagerBean;
import merlion.scm.rmpm.entity.RawMaterialItemLine;
import merlion.scm.rmpm.entity.RawMaterialPurchaseOrder;
import merlion.scm.rmpm.entity.RawMaterialSupplyInformation;
import merlion.scm.rmpm.entity.Supplier;
import merlion.scm.rmpm.entity.SupplierContactRecord;
import merlion.scm.rmpm.session.RawMaterialPurchaseSessionBeanLocal;
import org.primefaces.context.RequestContext;

@ManagedBean(name = "rmpoManagerBean")
@ViewScoped
public class RawMaterialPurchaseOrderManagerBean {

    private RawMaterialPurchaseOrder rmpo;
    private RawMaterialPurchaseOrder selectRmpo;
    private RawMaterialItemLine rmil;
    private RawMaterialItemLine rmilBackup;
    private String statusMsg;
    @EJB
    private RawMaterialPurchaseSessionBeanLocal rmpSessionBean;
    @ManagedProperty(value = "#{fileUploadManagerBean}")
    private FileUploadManagerBean fileManagerBean;

    //--------------------------------------------------------------------------
    //                          Constructor
    //--------------------------------------------------------------------------
    public RawMaterialPurchaseOrderManagerBean() {
        rmpo = (RawMaterialPurchaseOrder) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("rmpo");
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("rmpo");

        statusMsg = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("statusMsg");
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("statusMsg");
    }

    @PostConstruct
    public void init() {
        if (rmpo == null) {
            rmpo = new RawMaterialPurchaseOrder();
            rmpo.setPoNum(rmpSessionBean.generatePurchaseOrderNumber());
            rmil = new RawMaterialItemLine();
        }
    }

    //--------------------------------------------------------------------------
    //                          Manager Bean Methods
    //--------------------------------------------------------------------------
    public Collection<Supplier> getAllSupplier() {
        return rmpSessionBean.getAllSupplier();
    }

    public Collection<RawMaterialSupplyInformation> getSupplierRawMaterial() {
        return rmpo.getSupplier().getRawMaterialsSupplied();
    }

    public void addItemLine(ActionEvent event) {

        // Validate
        RequestContext context = RequestContext.getCurrentInstance();
        boolean valid = true;
        if (rmil.getRawMaterialSupplyInformation() == null || rmil.getRawMaterialSupplyInformation().getRawMaterial().getName().equals("")) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Raw Material is required", ""));
            valid = false;
        }
        if (rmil.getQty() == 0D) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Quantity cannot be zero", ""));
            valid = false;
        }
//        if (rmil.getQty() % rmil.getRawMaterialSupplyInformation().getRawMaterial().getLotSize() != 0L) {
//            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Quantity must be ordered in lot size", ""));
//            valid = false;
//        }
        ArrayList<RawMaterialItemLine> list = new ArrayList<RawMaterialItemLine>(rmpo.getItemLines());
        list.remove(rmil);
        boolean materialExist = false;
        for(RawMaterialItemLine r: list){
            if(rmil.getRawMaterialSupplyInformation().getRawMaterial().equals(r.getRawMaterialSupplyInformation().getRawMaterial()))
                materialExist = true;
        }
        if(materialExist){
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Raw material is already in order items", ""));
            valid = false;
        }
                
        context.addCallbackParam("valid", valid);
        if (!valid) {
            return;
        }

        rmil = rmpSessionBean.calculateLine(rmil);
        rmpo.getItemLines().add(rmil);

        rmil = new RawMaterialItemLine();
    }

    public void cancelAddItemLine(ActionEvent event) {
        rmil = new RawMaterialItemLine();
    }

    public void editItemLine(ActionEvent event) {
        rmil = (RawMaterialItemLine) event.getComponent().getAttributes().get("selected");
        rmilBackup = rmil.clone();
    }

    public void updateItemLine(ActionEvent event) {

        RequestContext context = RequestContext.getCurrentInstance();
        boolean valid = true;
        if (rmil.getRawMaterialSupplyInformation() == null || rmil.getRawMaterialSupplyInformation().getRawMaterial().getName().equals("")) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Raw Material is required", ""));
            valid = false;
        }
        if (rmil.getQty() == 0D) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Quantity cannot be zero", ""));
            valid = false;
        }
//        if (rmil.getQty() % rmil.getRawMaterialSupplyInformation().getRawMaterial().getLotSize() != 0L) {
//            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Quantity must be ordered in lot size", ""));
//            valid = false;
//        }
        context.addCallbackParam("valid", valid);
        if (!valid) {
            return;
        }

        rmil = rmpSessionBean.calculateLine(rmil);
        rmil = new RawMaterialItemLine();
    }

    public void cancelEditItemLine(ActionEvent event) {
        rmil.setQty(rmilBackup.getQty());
        rmil.setRawMaterialSupplyInformation(rmilBackup.getRawMaterialSupplyInformation());
        rmil.setSubtotalSGD(rmilBackup.getSubtotalSGD());
        rmil.setSubtotalUSD(rmilBackup.getSubtotalUSD());
    }

    public void removeItemLine(ActionEvent event) {
        rmil = (RawMaterialItemLine) event.getComponent().getAttributes().get("selected");
    }

    public void confirmRemoveItemLine(ActionEvent event) {
        rmpo.getItemLines().remove(rmil);
        rmil = new RawMaterialItemLine();
    }

    public void cancelRemoveItemLine(ActionEvent event) {
        rmil = new RawMaterialItemLine();
    }

    public String next() {

        // Validate

        boolean valid = true;
        if (rmpo.getSupplier() == null || rmpo.getSupplier().getSupplierName().equals("")) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Supplier is required", ""));
            valid = false;
        }
        if (rmpo.getItemLines().isEmpty()) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Order Items cannot be empty", ""));
            valid = false;
        }

        if (!valid) {
            return null;
        }

        rmpo = rmpSessionBean.calculatePurchaseOrder(rmpo);
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("rmpo", rmpo);

        return "createPurchaseOrderConfirm?faces-redirect=true";
    }

    public String confirm() {

        rmpo = rmpSessionBean.savePurchaseOrder(rmpo);

        if (rmpo != null) {
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("statusMsg", "Raw material purchase order successfully created.");
        } else {
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("statusMsg", "Raw material purchase order failed to create. Please try again.");
        }

        return "createPurchaseOrderStatus?faces-redirect=true";
    }
   
    public String cancelPurchaseOrder() {
         FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("statusMsg", "Raw material purchase order is cancelled.");
         return "createPurchaseOrderStatus?faces-redirect=true";
    }
    
    
    public String viewPurchaseOrderDisplay() {
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("rmpo", selectRmpo);
        return "viewPurchaseOrderDisplay?faces-redirect=true";
    }

    public List<RawMaterialPurchaseOrder> getAllPurchaseOrder() {
        return rmpSessionBean.getAllPurchaseOrder();
    }

    //--------------------------------------------------------------------------
    //                          Getter and Setter
    //--------------------------------------------------------------------------
    public RawMaterialPurchaseOrder getRmpo() {
        return rmpo;
    }

    public void setRmpo(RawMaterialPurchaseOrder rmpo) {
        this.rmpo = rmpo;
    }

    public RawMaterialItemLine getRmil() {
        return rmil;
    }

    public void setRmil(RawMaterialItemLine rmil) {
        this.rmil = rmil;
    }

    public RawMaterialItemLine getRmilBackup() {
        return rmilBackup;
    }

    public void setRmilBackup(RawMaterialItemLine rmilBackup) {
        this.rmilBackup = rmilBackup;
    }

    public String getStatusMsg() {
        return statusMsg;
    }

    public void setStatusMsg(String statusMsg) {
        this.statusMsg = statusMsg;
    }

    public RawMaterialPurchaseOrder getSelectRmpo() {
        return selectRmpo;
    }

    public void setSelectRmpo(RawMaterialPurchaseOrder selectRmpo) {
        this.selectRmpo = selectRmpo;
    }

    // send email , edited by zy Nov 9
    public void sendRawMaterialPurchaseOrderToSupplier(ActionEvent event) {
        // edited by ZY, 9 Nov 2011
        String res = "Raw material purchase order sent to supplier";
        String emailAddress = "";
        
        if (rmpo.getSupplier() == null || rmpo.getSupplier().getContacts() == null || rmpo.getSupplier().getContacts().isEmpty()){
            res = "rmpo is not able to sent to customer because no contact record is found.";
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Sending failed due to no contact record found", ""));
            statusMsg = "Sending failed due to no contact record found";
            System.out.println(res);
        } else {
            emailAddress = new ArrayList<SupplierContactRecord>(rmpo.getSupplier().getContacts()).get(0).getEmail();
            fileManagerBean.sendRawMaterialPurchaseOrder(emailAddress, rmpo.getId());
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO, "Sending successfully", "Sending successfully"));
            statusMsg = "Email sent successfully";
            System.out.println("#########################################email address: "+emailAddress);
        }
        
    }
    
    
    
    public FileUploadManagerBean getFileManagerBean() {
        return fileManagerBean;
    }

    public void setFileManagerBean(FileUploadManagerBean fileManagerBean) {
        this.fileManagerBean = fileManagerBean;
    }
}
